package cn.smxy.ln.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.smxy.ln.common.lang.Result;
import cn.smxy.ln.common.utils.RedisUtil;
import cn.smxy.ln.pojo.OssDto;
import cn.smxy.ln.pojo.WorkContent;
import cn.smxy.ln.pojo.WorkRegister;
import cn.smxy.ln.service.OssService;
import cn.smxy.ln.service.WorkContentService;
import cn.smxy.ln.service.WorkRegisterService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ln
 * @date 2022年05月24日 19:36
 */
@RestController
@RequestMapping("/workcontent")
public class WorkContentController {

    @Autowired
    WorkContentService workContentService;

    @Autowired
    WorkRegisterService workRegisterService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    OssService ossService;

    @GetMapping("/list")
    @HystrixCommand(fallbackMethod = "hystrixGetList")
    @Cacheable(cacheNames = "workContent", unless = "#result.getData() == null")    //key:缓存数据时使用的 key，可以用它来指定。默认是使用方法参数的值；cacheNames/value：二者选其一即可，指定缓存组件的名字
    public Result queryById(@RequestParam(value = "projectId", required = false) Long projectId, @RequestParam(value = "workId", required = false) Long workId, @RequestParam(value = "userId", required = false) Long userId, @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime, @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime, @RequestParam(value = "createTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date createTime) {
        QueryWrapper query = new QueryWrapper();
        if (projectId != null) {
            query.eq("project_id", projectId);
        }
        if (workId != null) {
            query.eq("work_id", workId);
        }
        if (userId != null) {
            query.eq("user_id", userId);
        }
        if (startTime != null && endTime != null && createTime != null) {
            return Result.fail("startTime，endTime，createTime不能同时有值，会矛盾");
        }
        if ((startTime != null && endTime == null) || (startTime == null && endTime != null)) {
            return Result.fail("startTime，endTime应该同时为空或同时不为空");
        }
        if (startTime == null && endTime == null && createTime != null) {
            query.eq("create_time", createTime);
        }
        if (startTime != null && endTime != null && createTime == null) {
            query.ge("create_time", startTime);
            query.le("create_time", endTime);
        }
        List<WorkContent> list = workContentService.list(query);
        if (list == null) {
            throw new RuntimeException("数据库没有该教师的workcontent数据，或者信息无法找到");
        }
        return Result.succ(list);
    }

    public Result hystrixGetList(Long projectId, Long workId, Long userId,  Date startTime, Date endTime, Date createTime) {
        return Result.fail("没有得到对应的workcontent信息，或者刷新试试");
    }

    /*@PostMapping("/save")
    @Transactional
    public Result save(OssDto ossDto) {
        if (ossDto.getProjectId() == null || ossDto.getProjectId().equals(""))
            return Result.fail("projectId不能为空，保存失败");
        if (ossDto.getWorkId() == null || ossDto.getWorkId().equals(""))
            return Result.fail("workId不能为空，保存失败");
        if (ossDto.getUserId() == null || ossDto.getUserId().equals(""))
            return Result.fail("userId不能为空，保存失败");

        String url = "";
        MultipartFile[] file = ossDto.getFile();
        WorkContent[] workContent = new WorkContent[file.length];
        for (int i = 0; i < file.length; i++) {
            workContent[i].setProjectId(ossDto.getProjectId());
            workContent[i].setWorkId(ossDto.getWorkId());
            workContent[i].setUserId(ossDto.getUserId());
        }
        for (int i = 0; i < file.length; i++) {
            url = ossService.uploadFileAvatar(file[i]);
            workContent[i].setFilePath(url);
            workContent[i].setCreateTime(DateUtil.date());
            workContentService.save(workContent[i]);
        }

        redisUtil.flushByX("workContent");
        return Result.succ(workContent);
    }*/
    @PostMapping("/save")
    @Transactional
    public Result save(@RequestParam(value = "projectId", required = false) Long projectId, @RequestParam(value = "workId", required = false) Long workId, @RequestParam(value = "userId", required = false) Long userId, @RequestParam(value = "workProveId", required = false) String workProveId, @RequestParam(value = "selfScore", required = false) Long selfScore, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("//获取文件并保存==================");
        List<WorkRegister> list = new ArrayList<>();
        List<WorkContent> list2 = new ArrayList<>();
        List list3 = new ArrayList();
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 判断是否是多数据段提交格式
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            WorkRegister workRegister = new WorkRegister();
            workRegister.setWorkId(workId);
            workRegister.setProjectId(projectId);
            workRegister.setTeacherId(userId);
            System.out.println("以下获取上传的非文件==");
            Map<String, String[]> parameterMap = multiRequest.getParameterMap();
            Set<String> keySet = parameterMap.keySet();
            String msg = "";
            String content = "";
            for (String key : keySet) {
                String[] strings = parameterMap.get(key);
                msg = Arrays.toString(strings);
                System.out.println(key + "===" + msg);
                if (key.equals("workContent")) {
                    content += msg;
                }
            }
            if (content.length() > 2)
            workRegister.setWorkContent(content.substring(1, content.length() - 1));
            workRegister.setWorkProveId(workProveId);
            workRegister.setSelfScore(selfScore);


            String workContentId = "";
            System.out.println("以下获取上传的文件==");
            Iterator<String> iter = multiRequest.getFileNames();
            //进入到这。iter中的已经全部是文件类型了
            Integer fileCount = 0;
            while (iter.hasNext()) {
                String next = iter.next();
                Part part = multiRequest.getPart(next);
                String name = part.getName();
                System.out.println(name);
                //TODO
                MultipartFile file = multiRequest.getFile(next);
                System.out.println(file);
                if (file == null) {
                    System.out.println("没有文件");
                    break;
                } else {
                    WorkContent workContent = new WorkContent();
                    workContent.setProjectId(projectId);
                    workContent.setWorkId(workId);
                    workContent.setUserId(userId);
                    workContent.setFilePath(ossService.uploadFileAvatar(file).get());
                    DateTime date = DateUtil.date();
                    workContent.setCreateTime(date);
                    boolean flag = workContentService.save(workContent);
                    if (flag) {
                        list2.add(workContent);
                        workContentId += workContent.getId() + ",";
                    }
                    fileCount++;
                }
            }
            if (workContentId.length() > 0) {
                workRegister.setCreateTime(DateUtil.date());
                workRegister.setWorkContentId(workContentId.substring(0, workContentId.length() - 1));
                boolean f = workRegisterService.save(workRegister);
                if (f) {
                    list.add(workRegister);
                    System.out.println(workRegister);
                }
            }
            System.out.println("本次提交文件类型的个数==" + fileCount);
        }
        list3.add(list);
        list3.add(list2);
        return Result.succ(list3);
    }


    @PostMapping("/delete")
    @Transactional
    public Result delete(@RequestParam Long id) {
        List<WorkRegister> workRegisters = workRegisterService.list();
        for (WorkRegister w: workRegisters) {
            String t = "";
            String[] st = w.getWorkContentId().split(",");
            for (int i = 0; i < st.length; i++) {
                if (Long.valueOf(st[i]) != id) {
                    if (t.equals("")) {
                        t += st[i];
                    } else {
                        t += "," + st[i];
                    }
                }
            }
            w.setWorkContentId(t);
            workRegisterService.updateById(w);
        }
        redisUtil.flushByX("workRegister");
        boolean flag = workContentService.removeById(id);
        if (flag) {
            redisUtil.flushByX("workContent");
            return Result.succ("删除成功");
        }
        return Result.fail("删除失败");
    }

    @PostMapping("/update")
    @Transactional
    public Result update(@RequestBody WorkContent workContent) {
        if (workContent.getProjectId() == null || workContent.getProjectId().equals(""))
            return Result.fail("projectId不能为空，更新失败");
        if (workContent.getWorkId() == null || workContent.getWorkId().equals(""))
            return Result.fail("workId不能为空，更新失败");
        if (workContent.getUserId() == null || workContent.getUserId().equals(""))
            return Result.fail("userId不能为空，更新失败");
        workContent.setCreateTime(DateUtil.date());
        boolean flag = workContentService.updateById(workContent);
        if (flag) {
            redisUtil.flushByX("workContent");
            return Result.succ(workContent);
        }
        return Result.fail("修改失败");
    }
}
